package com.edevp.common.security.service;

import com.edevp.common.core.util.jwt.JwtUtil;
import com.edevp.common.security.dto.AuthClientDTO;
import com.edevp.common.security.dto.AuthTokenDTO;
import com.edevp.common.security.dto.AuthUserDTO;
import com.edevp.common.security.constant.AuthConstants;
import com.edevp.common.security.util.TokenUtil;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lean
 * @create 2022-07-08 5:08 PM
 **/
@Component
public class AuthTokenService {
	public AuthTokenDTO createToken(AuthClientDTO client, AuthUserDTO user, int loginType){
		AuthTokenDTO authTokenDTO = new AuthTokenDTO();

		// Jwt存储信息
		Map<String, Object> claimsMap = new HashMap<>(3);
		claimsMap.put(AuthConstants.OAUTH_TOKEN_USER_ID, user.getUserId());
		claimsMap.put(AuthConstants.OAUTH_TOKEN_COMPANY_ID, user.getComId());
		claimsMap.put(AuthConstants.OAUTH_TOKEN_LOGIN_TYPE, loginType);
		// 生成token
		String token = JwtUtil.create(claimsMap);
		int expiresIn = client.getAccessTokenValiditySeconds();
		// 存入redis

		authTokenDTO.setToken(token);
		authTokenDTO.setExpire((long) expiresIn);
		authTokenDTO.setUser(user);

		TokenUtil.putToken(authTokenDTO,expiresIn);
		// 记录用户最后一次登录的时间、类型、设备
		return authTokenDTO;
	}

}
